<script setup lang="ts">
import {CaptchaApi, type LoginRO} from '@/api'
import {authService} from '@/service/AuthService'

const form = ref<LoginRO>({
  username: '',
  password: '',
  captcha: {
    id: '',
    value: ''
  }
})

const router = useRouter()
const captchaImg = ref<string>()
const captchaApi = new CaptchaApi()
const errorMsg = ref<string>()
const successMsg = ref<string>()
const needCatpcha = ref(false)

function loadCaptcha(){
  captchaApi.getCaptcha().then((response) => {
    captchaImg.value = response.data.imageBase64
    form.value.captcha!.id = response.data.id
  })
}

function login() {
  authService.login(form.value).then((response) => {
      successMsg.value = ""
      errorMsg.value = ""
      router.push('/')
    }).catch((err)=>{
    let errData = err.response.data
    if(errData.type == "LOGIN_CAPTCHA_ERROR"){
      needCatpcha.value = true
    }
    if (needCatpcha.value) {
      loadCaptcha()
    }
    errorMsg.value = errData.message
  })
}

function register() {
  authService.register(form.value).then(() => {
    errorMsg.value = ""
    successMsg.value = "注册成功!"
  }).catch((err)=>{
    let errData = err.response.data
    errorMsg.value = errData.message
  })
}

</script>

<template>
  <!--use element-plus-->
  <div class="h-screen bg-white flex items-center justify-center">
    <div class="w-96 bg-white rounded p-8 shadow-2xl">
      <div class="text-center text-2xl font-bold">注册/登录</div>
      <div class="pt-4">
        <ElForm :model="form" label-width="4em">
          <ElFormItem label="用户名">
            <ElInput data-testid="input-username" v-model="form.username" placeholder="用户名应不小于3字符，不大于10字符" />
          </ElFormItem>
          <ElFormItem label="密码">
            <ElInput data-testid="input-password" v-model="form.password" type="password" placeholder="密码应不短于5字符，不超过16字符" />
          </ElFormItem>
          <ElFormItem label="验证码" v-if="needCatpcha">
            <ElRow>
              <ElCol :span="10">
                <ElInput v-model="form.captcha!.value" placeholder="Captcha" />
              </ElCol>
              <ElCol :span="8" :offset="1">
                <img :src="captchaImg" alt="captcha" class="w-100px h-30px" @click="loadCaptcha" />
              </ElCol>
            </ElRow>
          </ElFormItem>
          <ElFormItem v-if="errorMsg" label="">
            <div data-testid="error-msg" class="text-red-500">{{ errorMsg }}</div>
          </ElFormItem>
          <ElFormItem v-if="successMsg" label="">
            <div data-testid="success-msg" class="text-green-500">{{ successMsg }}</div>
          </ElFormItem>
          <ElFormItem>
            <ElButton data-testid="login-button" type="primary" @click="login" class="w-full">登录</ElButton>
          </ElFormItem>
          <ElFormItem>
            <ElButton type="primary" @click="register" class="w-full">注册</ElButton>
          </ElFormItem>
        </ElForm>
      </div>
    </div>
  </div>
</template>

<style scoped>

</style>
